<template>
  <div class="volunteer-approval">
    <div class="header">
      <h2>志愿者申请审批</h2>
      <p>审批用户提交的志愿者申请</p>
    </div>

    <div class="content">
      <!-- 筛选和操作区域 -->
      <div class="filter-section">
        <div class="filter-group">
          <label>申请状态：</label>
          <select v-model="filterStatus" @change="fetchApplications">
            <option value="">全部</option>
            <option value="pending">待审批</option>
            <option value="approved">已通过</option>
            <option value="rejected">已拒绝</option>
          </select>
        </div>
        <button class="refresh-btn" @click="fetchApplications">刷新列表</button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <p>加载中...</p>
      </div>

      <!-- 申请列表 -->
      <div class="application-list" v-else-if="applications.length > 0">
        <div class="application-item" v-for="app in applications" :key="app.volunteerID">
          <div class="application-header">
            <span class="applicant-name">{{ app.name || '匿名用户' }}</span>
            <span class="application-time">{{ formatTime(app.applyTime) }}</span>
          </div>

          <div class="application-content">
            <div class="info-row">
              <label>联系电话：</label>
              <span>{{ app.phone || '未提供' }}</span>
            </div>
            <div class="info-row">
              <label>邮箱：</label>
              <span>{{ app.email || '未提供' }}</span>
            </div>
            <div class="info-row">
              <label>部门：</label>
              <span>{{ app.department || '未提供' }}</span>
            </div>
            <div class="info-row">
              <label>职位：</label>
              <span>{{ app.position || '未提供' }}</span>
            </div>
            <div class="info-row">
              <label>相关经历：</label>
              <span class="experience">{{ app.experience || '无' }}</span>
            </div>
            <div class="info-row">
              <label>当前状态：</label>
              <span :class="['status', app.status]">{{ getStatusText(app.status) }}</span>
            </div>

            <!-- 审核信息 -->
            <div v-if="app.status !== 'pending'" class="review-info">
              <div class="info-row">
                <label>审核意见：</label>
                <span>{{ app.reviewNotes || '无' }}</span>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons" v-if="app.status === 'pending'">
            <button class="btn-approve" @click="approveApplication(app)">通过申请</button>
            <button class="btn-reject" @click="rejectApplication(app)">拒绝申请</button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <p>暂无志愿者申请</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

interface VolunteerApplication {
  volunteerID: number
  userID: number
  name: string
  phone: string
  email: string
  department: string
  position: string
  experience: string
  status: string
  applyTime: string
  reviewNotes?: string
  reviewTime?: string
}

// 响应式数据
const applications = ref<VolunteerApplication[]>([])
const filterStatus = ref('')
const loading = ref(false)

// 后端API基础URL
const API_BASE = 'http://localhost:8080'

// 生命周期
onMounted(() => {
  fetchApplications()
})

// 获取申请列表
const fetchApplications = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token') || ''

    const response = await fetch(`${API_BASE}/manager/getAllVolunteerApplications`, {
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.success) {
      let data = result.data || []

      // 根据筛选状态过滤
      if (filterStatus.value) {
        data = data.filter((app: VolunteerApplication) => app.status === filterStatus.value)
      }

      applications.value = data
    } else {
      alert(result.msg || '获取申请列表失败')
    }
  } catch (error) {
    console.error('获取志愿者申请失败:', error)
    alert('网络错误，请检查后端服务是否启动')
  } finally {
    loading.value = false
  }
}

// 通过申请
const approveApplication = async (app: VolunteerApplication) => {
  if (confirm(`确定要通过 ${app.name} 的志愿者申请吗？`)) {
    await updateApplicationStatus(app.volunteerID, 'approved', '')
  }
}

// 拒绝申请
const rejectApplication = async (app: VolunteerApplication) => {
  const reason = prompt('请输入拒绝理由（可选）：', '')
  if (reason !== null) {
    await updateApplicationStatus(app.volunteerID, 'rejected', reason)
  }
}

// 更新申请状态
const updateApplicationStatus = async (applicationId: number, status: string, reviewNotes: string) => {
  try {
    const token = localStorage.getItem('token') || ''

    const applicationData = {
      volunteerID: applicationId,
      status: status,
      reviewNotes: reviewNotes
    }

    const response = await fetch(`${API_BASE}/manager/approveVolunteerApplication`, {
      method: 'POST',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(applicationData)
    })

    const result = await response.json()

    if (result.success) {
      alert(result.msg || '审批成功')
      fetchApplications()
    } else {
      alert(result.msg || '审批失败')
    }
  } catch (error) {
    console.error('审批操作失败:', error)
    alert('网络错误，请稍后重试')
  }
}

// 工具函数
const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': '待审批',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

const formatTime = (timeString: string) => {
  if (!timeString) return '-'
  return new Date(timeString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.volunteer-approval {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  color: #2E7D32;
  font-size: 2rem;
  margin-bottom: 10px;
}

.header p {
  color: #666;
  font-size: 1.1rem;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: bold;
  color: #333;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.refresh-btn {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.refresh-btn:hover {
  background: #1976D2;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.application-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.application-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.application-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.applicant-name {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
}

.application-time {
  color: #666;
  font-size: 0.9rem;
}

.application-content {
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.info-row label {
  font-weight: bold;
  color: #333;
  min-width: 100px;
}

.experience {
  flex: 1;
  line-height: 1.4;
  white-space: pre-wrap;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: bold;
}

.status.pending {
  background: #FFF3E0;
  color: #EF6C00;
}

.status.approved {
  background: #E8F5E8;
  color: #2E7D32;
}

.status.rejected {
  background: #FFEBEE;
  color: #C62828;
}

.review-info {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.btn-approve, .btn-reject {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.btn-approve {
  background: #4CAF50;
  color: white;
}

.btn-approve:hover {
  background: #45a049;
}

.btn-reject {
  background: #f44336;
  color: white;
}

.btn-reject:hover {
  background: #da190b;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-state p {
  font-size: 1.2rem;
}
</style>
